import React, { useState, useEffect, useCallback, useRef } from "react";
import { useNavigate } from "react-router-dom";
import { Toast } from "@nutui/nutui-react";
import TopNav from "../../../components/topNav";
import { userFollowService, handleApiResponse, handleApiError } from "../../../utils/api";
import type { FollowedDoctor } from "../../../type";
import "./index.css";

const UserFollow: React.FC = React.memo(() => {
  const navigate = useNavigate();
  const [doctorList, setDoctorList] = useState<FollowedDoctor[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [error, setError] = useState<string>("");

  // 获取关注医生列表
  const getFollowDoctorList = useCallback(async () => {
    setLoading(true);
    setError("");

    try {
      const response = await userFollowService.getUserFollowDoctorList({
        page: 1,
        count: 20
      });
      
      const result = handleApiResponse<FollowedDoctor[]>(response);
      setDoctorList(result || []);
    } catch (err) {
      const errorMessage = handleApiError(err);
      setError(errorMessage);
      Toast.show(errorMessage);
      console.error('获取关注医生列表失败:', err);
    } finally {
      setLoading(false);
    }
  }, []);

  // 取消关注医生
  const handleCancelFollow = useCallback(async (doctorId: number, doctorName: string) => {
    try {
      await userFollowService.cancelFollowDoctor(doctorId);
      Toast.show(`已取消关注${doctorName}`);
      
      // 从列表中移除该医生
      setDoctorList(prev => prev.filter(doctor => doctor.doctorId !== doctorId));
    } catch (err) {
      const errorMessage = handleApiError(err);
      Toast.show(errorMessage);
      console.error('取消关注失败:', err);
    }
  }, []);

  // 计算好评率
  const calculatePraiseRate = useCallback((praiseNum: number, badNum: number): number => {
    const total = praiseNum + badNum;
    if (total === 0) return 0;
    return Math.round((praiseNum / total) * 100);
  }, []);

  // 页面加载时获取数据
  useEffect(() => {
    getFollowDoctorList();
  }, [getFollowDoctorList]);

  // 医生卡片组件
  const DoctorCard = React.memo(({ doctor }: { doctor: FollowedDoctor }) => {
    const praiseRate = calculatePraiseRate(doctor.praiseNum, doctor.badNum);
    const cardRef = useRef<HTMLDivElement>(null);
    const [isSwipeOpen, setIsSwipeOpen] = useState(false);

    const handleTouchStart = useCallback((e: React.TouchEvent) => {
      const startX = e.touches[0].clientX;
      const card = cardRef.current;
      if (!card) return;

      const handleTouchMove = (moveEvent: TouchEvent) => {
        const currentX = moveEvent.touches[0].clientX;
        const diffX = startX - currentX;
        
        if (diffX > 0) {
          card.style.transform = `translateX(-${Math.min(diffX, 80)}px)`;
        }
      };

      const handleTouchEnd = (endEvent: TouchEvent) => {
        const endX = endEvent.changedTouches[0].clientX;
        const diffX = startX - endX;
        
        if (diffX > 40) {
          setIsSwipeOpen(true);
          card.style.transform = 'translateX(-80px)';
        } else {
          setIsSwipeOpen(false);
          card.style.transform = 'translateX(0)';
        }
        
        document.removeEventListener('touchmove', handleTouchMove);
        document.removeEventListener('touchend', handleTouchEnd);
      };

      document.addEventListener('touchmove', handleTouchMove);
      document.addEventListener('touchend', handleTouchEnd);
    }, []);

    const handleCancelClick = useCallback(() => {
      handleCancelFollow(doctor.doctorId, doctor.name);
      setIsSwipeOpen(false);
      if (cardRef.current) {
        cardRef.current.style.transform = 'translateX(0)';
      }
    }, [doctor.doctorId, doctor.name]);

    return (
      <div className="swipe-container">
        <div 
          ref={cardRef}
          className="doctor-card"
          onTouchStart={handleTouchStart}
          style={{ transform: isSwipeOpen ? 'translateX(-80px)' : 'translateX(0)' }}
        >
          <div className="doctor-avatar">
            <img src={doctor.imagePic} alt={doctor.name} />
          </div>
          <div className="doctor-info">
            <div className="doctor-name-row">
              <span className="doctor-name">{doctor.name}</span>
              <span className="doctor-title">{doctor.jobTitle}</span>
            </div>
            <div className="doctor-hospital">
              {doctor.inauguralHospital}/{doctor.departmentName}
            </div>
            <div className="doctor-stats">
              <span className="praise-rate">好评率 {praiseRate}%</span>
              <span className="patient-count">服务患者数 {doctor.number}</span>
            </div>
          </div>
        </div>
        <div className="swipe-action">
          <button className="cancel-follow-btn" onClick={handleCancelClick}>
            取消关注
          </button>
        </div>
      </div>
    );
  });

  return (
    <div className="user-follow-page">
      <TopNav title="我的关注" />
      
      <div className="follow-content">
        {loading ? (
          <div className="loading">加载中...</div>
        ) : error ? (
          <div className="error-message">{error}</div>
        ) : doctorList.length === 0 ? (
          <div className="empty-state">
            <p>暂无关注的医生</p>
          </div>
        ) : (
          <div className="doctor-list">
            {doctorList.map((doctor) => (
              <DoctorCard key={doctor.id} doctor={doctor} />
            ))}
          </div>
        )}
      </div>
    </div>
  );
});

UserFollow.displayName = 'UserFollow';

export default UserFollow;